import {getToken, removeToken, setToken} from "@/utils/tools/auth";
import {defineStore} from 'pinia'
import {getInfo, logout,} from "@/api/auth";
import {formatUrlAvatar} from "@/utils/tools/format";

export const useUserStore = defineStore("user",{
    state: () => ({
        token: getToken(),
        status:false,
        user:{
            id:0,
            admin:false,
            phonenumber:null,
        },
        roles:[],
        adminList:["admin","blog-admin"]
    }),
    getters: {
        id:(state)=>{
            // console.log(state.user)
            return state.user.userId || 0;
        },
        userName:(state)=>{
            return state.user.userName || "";
        },
        nickName:(state)=>{
            return state.user.nickName || "";
        },
        email:(state)=>{
            return state.user.email || "";
        },
        avatar:(state)=>{
            return formatUrlAvatar(state.user.avatar || "")
        },
        role:(state)=>{
            //state.roles 是一个包含用户角色的数组
            const isAdmin = state.roles.some(role => state.adminList.includes(role));
            // 根据检查结果返回相应的角色标签
            return isAdmin ? "管理员" : "用户";
        },
        isAdmin:(state)=>{
            //state.roles 是一个包含用户角色的数组
            return state.roles.some(role => state.adminList.includes(role));
        },
        phoneNumber:(state)=>{
            return state.user.phonenumber
        },
    },
    persist: true, //开启持久化
    actions: {
        // 获取用户信息
        getUser() {
            return new Promise((resolve, reject) => {
                getInfo().then(res => {
                    this.user = res.user;
                    this.status=true;
                    this.roles = res.roles;
                    // console.log(res )
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 登录成功
        loginSuccess(res){
            setToken(res.token)
            this.token = res.token;
            this.getUser(this.token);
        },
        // 退出系统
        logOut() {
            return new Promise((resolve, reject) => {
                logout().then(() => {
                    this.clearStore()
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        removeUserInfo(){
            this.user ={};
            this.status =false;
        },
        clearStore(){
            removeToken(),
            this.removeUserInfo()
        },
    }

})
